
//
//  ImageView+Network.swift
//  Extend
//
//  Created by shufang zou on 2017/8/23.
//  Copyright © 2017年 敬信. All rights reserved.
//
import Foundation
import Kingfisher

public extension UIImageView {
    // 360度旋转图片
    func rotate360Degree() {
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z") // 让其在z轴旋转
        rotationAnimation.toValue = NSNumber(value: M_PI * 2.0) // 旋转角度
        rotationAnimation.duration = 1 // 旋转周期
        rotationAnimation.isCumulative = true // 旋转累加角度
        rotationAnimation.repeatCount = 1000000 // 旋转次数
        layer.add(rotationAnimation, forKey: "rotationAnimation")
    }
    
    // 停止旋转
    func stopRotate() {
        layer.removeAllAnimations()
    }
    
    /*******  loadImage   *********/
    
    struct Keys {
        static fileprivate var url: String = String();
        static fileprivate var renderer: String = String();
        static fileprivate var interceptors: String = String();
        static fileprivate var placeHolder: String = String();
    }
    
    fileprivate var url: String {
        get {
            return associated(to: self, key: &Keys.url) {
                String()
            };
        }
        set {
            associate(to: self, key: &Keys.url, value: newValue);
        }
    }
    
    private var renderer: Renderer {
        get {
            
            return associated(to: self, key: &Keys.renderer) {
                self.renderer;
            };
        }
        set {
            associate(to: self, key: &Keys.renderer, value: newValue);
        }
    }
    
    private var interceptors: Array<Interceptor> {
        get {
            return associated(to: self, key: &Keys.interceptors) {
                Array()
            };
        }
        set {
            associate(to: self, key: &Keys.interceptors, value: newValue);
        }
    }
    
    private var placeHolder: String {
        get {
            return associated(to: self, key: &Keys.placeHolder) {
                String()
            };
        }
        set {
            associate(to: self, key: &Keys.placeHolder, value: newValue)
        }
    }
    
    
    public func url(_ u: String) -> Self {
        url = u;
        return self;
    }
    
    public func renderer(_ r: Renderer) -> Self {
        renderer = r;
        return self;
    }
    
    public func placeHolder(_ image: String) -> Self {
        placeHolder = image;
        return self;
    }
    
    public func interceptor(i: Interceptor) -> Self {
        interceptors.append(i);
        return self;
    }
    
    
    public func loadRender() {
        if self.url .isEmpty {
            return;
        }
        
        if (self.renderer is CircleRenderer) {
            let circle = self.renderer as! CircleRenderer;
            self.layer.borderWidth = CGFloat(circle.borderWidth);
            self.layer.borderColor = circle.borderColor.cgColor;
            
        }else if (self.renderer is CornerRendener) {
            let corder = self.renderer as! CornerRendener;
            self.layer.cornerRadius = corder.redius;
            self.layer.masksToBounds = true;
        }
        
        load();
    }
    
    
    
    public func load() {
        if self.url .isEmpty {
            if !self.placeHolder.isEmpty {
                self.setInterceptImage(UIImage(named: self.placeHolder)!);
            }
            return
        }
        
//        let cache = KingfisherManager.shared.cache
//        //最大缓存消耗512m内存
//        cache.maxMemoryCost = 512 * 1024 * 1024
        
        if  self.placeHolder.isEmpty  {
            self.kf.setImage(with: URL(string: self.url), placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (img, error, cacheType, imageURL) in
                
                if img != nil {
                    self.setInterceptImage(img!);
                }
            })
            
        } else {
            self.kf.setImage(with: URL(string: self.url), placeholder: UIImage(named: self.placeHolder), options: nil, progressBlock:  { receivedSize, totalSize in
                
            }, completionHandler: {  (img, error, cacheType, imageURL) in
    
                self.setInterceptImage((img ?? UIImage(named: self.placeHolder)!));
            })
        }
    }
    
    func setInterceptImage(_ image:UIImage) {
        var interceptImage = image;
        for hander in interceptors {
            if (hander is CutInterceptor) {
                let h = (hander as! CutInterceptor)
                interceptImage = UIImage.cutOut(interceptImage, rect: h.cutRect);
            }
            if (hander is BlurInterceptor) {
                let h = (hander as! BlurInterceptor)
                interceptImage = UIImage.blurFilter(interceptImage, blur: h.alpha);
            }
            if (hander is ResizeInterceptor) {
                let h = (hander as! ResizeInterceptor)
                interceptImage = UIImage.resSize(interceptImage, size: h.size);
            }
        }
        self.image = interceptImage;
    }
}

public protocol Renderer {
    
}

open class CircleRenderer: Renderer {
    public var borderWidth = NSInteger();
    public var borderColor = UIColor();
    public init() {
        
    }
}

open class CornerRendener: Renderer {
    public var redius = CGFloat();
    public init() {
        
    }
}

public protocol Interceptor {
    
}

open class CutInterceptor: Interceptor {
    public var cutRect = CGRect();
    public init() {
        
    }
}

open class BlurInterceptor: Interceptor {
    public var alpha = CGFloat();
    public init() {
        
    }
}

open class ResizeInterceptor: Interceptor {
    public var size = CGSize();
    public init() {
    }
}

public extension UIImageView {
    
    /// 部分圆角
    ///
    /// - Parameters:
    ///   - corners: 需要实现为圆角的角，可传入多个
    ///   - radii: 圆角半径
    func corner(byRoundingCorners corners: UIRectCorner, radii: CGFloat) {
        let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radii, height: radii))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
    }
}

